function ajaxPost(url, data, successback, errerback) {
  login(function () {
    ajax(url, data, "POST", successback, errerback);
  });
}

function ajaxGet(url, data, successback, errerback) {
  ajax(url, data, "Get", successback, errerback);
}

function ajaxBasePost(url, data, successback, errerback) {
  ajax2(url, data, "POST", successback, errerback);
}

function ajaxBaseGet(url, data, successback, errerback) {
  ajax2(url, data, "Get", successback, errerback);
}

function getRootUrl()
{
  // return "http://localhost:22931/";
  // return "http://120.25.212.63:8082/";
  return "http://111.230.228.224/";
}

function login(callback)
{
  if (wx.getStorageSync("authToken") == null || wx.getStorageSync("authToken") == "")
  {
    let that = this;    
    wx.login({
      success: function (res) { 
        if (res.code) {  
          let code = res.code;
          let openSetting = wx.getStorageSync("openSetting");
          if (wx.getStorageSync("openSetting") == true) {
            wx.openSetting({
              success: function (data) {
                if (data) {
                  if (data.authSetting["scope.userInfo"] == true) {
                    getUserInfo(code, callback);
                  }
                }
              }
            });
          }
          else{
            getUserInfo(code, callback);
          }
        } 
      }
    });
  }
  else{
    if (callback) { callback();}
  }
}
function getUserInfo(code, callback) {
  // wx.hideLoading();
  wx.getUserInfo({
    success: function (res) {
      wx.setStorageSync("openSetting", false);
      let param = {};
      param.code = code;
      param.encryptedData = res.encryptedData;
      param.iv = res.iv;
      param.ClientId = "62ccad6d-9611-41c5-96f6-08ec0ada0f68";
      param.ClientSecret = "5678";
      param.TokenType = 2;
      ajax2("api/WeChart/GetMiniOpenId", param, "POST", function (d) {
        let data = d.data;
        if (d.suc) {
          setCache(data);
          if (data.AccessToken != null && data.AccessToken != "") {
            if (callback) { callback(); }
          } else {
            var pages = getCurrentPages()    //获取加载的页面
            var currentPage = pages[pages.length - 1]    //获取当前页面的对象
            var url = currentPage.route    //当前页面url
            if (url) {
              let index = 2;
              if (url.toLowerCase() == "pages/index/index") {
                index = 2;
              } else if (url.toLowerCase() == "pages/startbluetooth/startblue") {
                index = 1;
              } else if (url.toLowerCase() == "pages/mycenter/mycenter") {
                index = 3;
              }
              wx.redirectTo({
                url: "/pages/noRegister/noregister?id=" + index + '&openId='
                + data.OpenId + '&unionId=' + data.UnionId
              });
            }
          }
        }
      });
    },
    fail: function (res) {
      wx.setStorageSync("openSetting", true);
      wx.redirectTo({
        url: "/pages/index/index"
      });
    }
  });  
}
function setCache(data) {
  wx.setStorageSync("unionId", data.UnionId);
  wx.setStorageSync("openId", data.OpenId); 
  wx.setStorageSync("authToken", data.AccessToken);
  wx.setStorageSync("refreshToken", data.RefreshToken);
  wx.setStorageSync("customerName", data.CustomerName);
  wx.setStorageSync("headImg", data.HeadImg);
  wx.setStorageSync("sex", data.Sex);
  wx.setStorageSync("tel", data.Tel);
  wx.setStorageSync("customerId", data.ID);
  wx.setStorageSync("cityId", data.CityId);
  wx.setStorageSync("CircleName", data.CircleName);
}
 /**
   * ajax请求
   * requesturl:请求地址
   * data:json数据
   * type:请求类型
   * successback:成功回调如无需要可填null
   * errorback:失败回调,如无需要可填null
   */
function ajax(requesturl, data, type, successback, errorback) {  
  var baseUrl = getRootUrl();   
  var header = {};
  header["Content-Type"] = "application/json"; 
  if (!type) {
    type = "POST";
  }
  var d = {};
  d.Url = baseUrl + requesturl;//todo:这里的访问网址需要替换
  d.HttpMethod = 1;
  d.Device = 5;
  d.Token = wx.getStorageSync("authToken");
  if (!data) {
    data = {};
  }
  if (!data.UserId)
  data.UserId = wx.getStorageSync("customerId");
  data.Token=d.Token;
  d.RequestParas = typeof data !== 'string' ? JSON.stringify(data) : data;

  wx.request({
    url: baseUrl + "api/Base/Index",
    data: JSON.stringify(d),
    method: type,
    header: header, // 设置请求的 header
    success: function (res) {
      if (res.data.statusCode=="110"){
        wx.setStorageSync("authToken", null);
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length - 1]    //获取当前页面的对象
        var url = currentPage.route    //当前页面url
        if(url){
          let param = "";
          for (let option in currentPage.options) {
            param += option + "=" + currentPage.options[option] + "&";
          }
          if (param.length > 0) {
            param = "?" + param.substring(0, param.length - 1);
          }
          wx.navigateTo({
            url: url + param
          });
        }        
      }
      else if (successback) {
        successback(res.data);
      }
    },
    fail: function (res) {
      if (errorback) {
        errorback(res);
      }
    }
  }); 
}

 /**
   * ajax请求
   * requesturl:请求地址
   * data:json数据
   * type:请求类型
   * successback:成功回调如无需要可填null
   * errorback:失败回调,如无需要可填null
   */
function ajax2(requesturl, data, type, successback, errorback) {
  var baseUrl = getRootUrl(); 
  data.Token = wx.getStorageSync("authToken");
  if (typeof data !== 'string') {
    data = JSON.stringify(data);
  }
  if (!type) {
    type = "POST";
  } 
  var header = {};
  header["Content-Type"] = "application/json"; 
  wx.request({
    url: baseUrl + requesturl,
    data: data,
    method: type, 
    header: header, // 设置请求的 header
    success: function (res) {
      if (res.data.statusCode == "110") {
        wx.setStorageSync("authToken", null);
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length - 1]    //获取当前页面的对象
        var url = currentPage.route    //当前页面url
        if (url) {
          let param = "";
          for (let option in currentPage.options) {
            param += option + "=" + currentPage.options[option] + "&";
          }
          if (param.length > 0) {
            param = "?" + param.substring(0, param.length - 1);
          }
          wx.navigateTo({
            url: url + param
          });
        }       
      }
      else if (successback) {
        successback(res.data);
      }
    },
    fail: function (res) {
      if (errorback) {
        errorback(res);
      }
    },complete:function(res){
      let result=res;
    }
  });
}

module.exports = {
  ajaxPost: ajaxPost,
  ajaxGet: ajaxGet,
  ajaxBasePost: ajaxBasePost,
  ajaxBaseGet: ajaxBaseGet,
  getRootUrl: getRootUrl,
  login: login,
  setCache:setCache
}